import { desktopCapturer, ipcRenderer } from "electron";
const EventEmitter = require("events");
const peer = new EventEmitter();

async function getScreenStream() {
  // desktopCapturer 从桌面捕获音频和视频的媒体源信息
  const sources = await desktopCapturer.getSources({
    types: ["screen"],
  });

  // 从指定的媒体源获取媒体流信息
  return new Promise((resolve, reject) => {
    navigator.mediaDevices
      .getUserMedia({
        audio: false,
        video: {
          mandatory: {
            chromeMediaSource: "desktop",
            chromeMediaSourceId: sources[0].id,
            maxWidth: window.screen.width,
            maxHeight: window.screen.height,
          },
        },
      })
      .then((stream) => {
        // 触发 add-stream 事件，将视频流传过去播放
        peer.emit("add-stream", stream);
        resolve(stream);
      })
      .catch((err) => {
        console.log(err);
        reject(err);
      });
  });
}

const pc = new window.RTCPeerConnection({});

pc.ondatachannel = (e) => {
  console.log("datachannel", e);
  e.channel.onmessage = (e) => {
    let { type, data } = JSON.parse(e.data);
    if (type === "mouse") {
      data.screen = {
        width: window.screen.width,
        height: window.screen.height,
      };
    }
    ipcRenderer.send("robot", type, data);
  };
};

pc.onicecandidate = function (e) {
  console.log("candidate", JSON.stringify(e.candidate));
  if (e.candidate) {
    ipcRenderer.send(
      "forward",
      "puppet-candidate",
      JSON.stringify(e.candidate)
    );
  }
};

ipcRenderer.on("candidate", (e, candidate) => {
  addIceCandidate(candidate);
});

let candidates = [];
async function addIceCandidate(candidate) {
  if (candidate) {
    candidates.push(candidate);
  }
  if (pc.remoteDescription && pc.remoteDescription.type) {
    for (let i = 0; i < candidates.length; i++) {
      await pc.addIceCandidate(new RTCIceCandidate(JSON.parse(candidates[i])));
    }
    candidates = [];
  }
}
window.addIceCandidate = addIceCandidate;

ipcRenderer.on("offer", async (e, offer) => {
  let answer = await createAnswer(offer);
  ipcRenderer.send("forward", "answer", { type: answer.type, sdp: answer.sdp });
});

async function createAnswer(offer) {
  let screenStream = await getScreenStream();

  pc.addStream(screenStream);
  await pc.setRemoteDescription(offer);
  await pc.setLocalDescription(await pc.createAnswer());
  console.log("answer", JSON.stringify(pc.localDescription));

  return pc.localDescription;
}

window.createAnswer = createAnswer;
